<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    :show-close="false"
    :close-on-click-modal="false"
    width="700px"
    center
  >
    <el-form :model="formData">
      <el-form-item label="上级菜单">
        <el-tree-select
          v-model="formData.parentId"
          :data="parentMenuArr"
          check-strictly="true"
          node-key="id"
          accordion
          :props="{
            value: 'id',
            label: 'name',
            children: 'children',
          }"
        />
      </el-form-item>
      <el-form-item label="菜单类型">
        <el-radio-group v-model="formData.type">
          <el-radio
            v-for="item in menuType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            >{{ item.label }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item label="菜单图标">
        <el-input placeholder="请选择图标" v-model="formData.icon" autocomplete="off" />
      </el-form-item>
      <el-form-item label="菜单名称">
        <el-input v-model="formData.name" placeholder="请输入菜单名称" autocomplete="off" />
      </el-form-item>
      <el-form-item label="组件名称">
        <el-input v-model="menuData.component" placeholder="请输入组件名称" autocomplete="off" />
      </el-form-item>
      <el-form-item label="排序">
        <el-input-number v-model="formData.sort" :min="1" />
      </el-form-item>
      <el-form-item label="是否展示">
        <el-switch v-model="menuData.isVisible" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closeDialog">返回</el-button>
      <el-button type="primary" @click="submitDialog">提交</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts">
export default {
  name: 'MenuDialog',
}
</script>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { SysMenu } from '@/types/index'
import { menuType } from '@/utils/dicts/menu'
import emitter from '@/utils/emitter'
import { addMenu, updateMenu } from '@/http/api'

const props = defineProps({
  displayFlag: {
    type: Boolean,
  },
  title: {
    type: String,
  },
  parentMenuList: {
    type: Object as () => SysMenu[],
  },
  menuData: {
    type: Object as () => SysMenu,
    required: true,
  },
})

const dialogVisible = ref(props.displayFlag)
const dialogTitle = ref(props.title)
const formData = reactive<SysMenu>(props.menuData)
const parentMenuArr = ref([
  {
    id: 0,
    name: '根目录',
    children: props.parentMenuList,
  },
])
const closeDialog = () => {
  emitter.emit('update:displayFlag', false)
  emitter.emit('refresh:menuTableData')
}
const submitDialog = () => {
  if (!formData.id) {
    addMenu(formData)
      .then(() => {
        closeDialog()
      })
      .catch((err) => {
        console.log(err)
      })
  } else {
    updateMenu(formData)
      .then(() => {
        closeDialog()
      })
      .catch((err) => {
        console.log(err)
      })
  }
}
</script>
